package com.wink_172.library.activity

import android.content.Context
import android.content.Intent
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import com.wink_172.library.R
import com.wink_172.library.databinding.ActivityWebBinding
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.FileUtil
import com.wink_172.library.view.ActionBarView

class WebActivity : SmartActivity() {
    lateinit var mWeb: WebView
    lateinit  var binding: ActivityWebBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarLightMode()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_web)

        initView()
        initWebView()
        init()
    }

    private fun initView() {}
    private fun init() {
        val title = intent.getStringExtra(Constants.PARAM_DATA1)

        (binding!!.actionBar as ActionBarView).updateAllContent(R.mipmap.icon_back, title, "");
        (binding!!.actionBar as ActionBarView).setCallback (object : ActionBarView.ICallback {
            override fun onSendEvent(event: Int, content: String?) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish()
                }
            }
        })

        val url = intent.getStringExtra(Constants.PARAM_DATA2)
        loadUrl(url)
    }

    private fun initWebView() {
        mWeb = WebView(this)
        val param = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        mWeb!!.scrollBarStyle = WebView.SCROLLBARS_OUTSIDE_OVERLAY
        mWeb!!.overScrollMode = WebView.OVER_SCROLL_NEVER
        mWeb!!.setBackgroundColor(resources.getColor(android.R.color.white))
        mWeb!!.layoutParams = param
        binding!!.web.addView(mWeb)
        initWebViewSettings(mWeb!!)
        setWebClientConfig(mWeb!!)
        //        addJsNativeInterface(mWeb);
    }

    private fun initWebViewSettings(web: WebView) {
        CookieSyncManager.createInstance(this)
        val cm = CookieManager.getInstance()
        cm.setAcceptCookie(true)
        val settings = web.settings
        settings.setSupportZoom(true)
        settings.builtInZoomControls = false
        settings.javaScriptEnabled = true
        settings.domStorageEnabled = true
        settings.databaseEnabled = true
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        val cache = FileUtil.getAppFilesDir("cache")
        val cachePath = if (cache != null && cache.exists()) cache.path else cacheDir.path
        settings.databasePath = cachePath
        settings.setAppCachePath(cachePath)
        settings.setAppCacheEnabled(true)
    }

    private fun setWebClientConfig(view: WebView) {
        view.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                if (!TextUtils.isEmpty(url) && url.startsWith(WebView.SCHEME_TEL)) {
                    return true
                }
                view.loadUrl(url)
                return true
            }

//            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {}
            override fun onPageFinished(view: WebView, url: String) {}
            override fun onReceivedSslError(
                view: WebView,
                handler: SslErrorHandler,
                error: SslError
            ) {
                showSslError(handler, error)
            }
        }
        view.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                if (view.canGoBack()) {
                }
            }

            override fun onProgressChanged(view: WebView, newProgress: Int) {}
        }
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                view.removeJavascriptInterface("searchBoxJavaBridge_")
                view.removeJavascriptInterface("accessibility")
                view.removeJavascriptInterface("accessibilityTraversal")
            }
        } catch (e: Exception) {
        }
    }

    /**
     * 谷歌上架必须要调用该方法
     */
    private fun showSslError(handler: SslErrorHandler, error: SslError) {
        val builder = AlertDialog.Builder(this@WebActivity)
        var message = "SSL Certificate error."
        val bb = error.primaryError
        message = when (bb) {
            SslError.SSL_UNTRUSTED -> "The certificate authority is not trusted."
            SslError.SSL_EXPIRED -> "The certificate has expired."
            SslError.SSL_IDMISMATCH -> "The certificate Hostname mismatch."
            SslError.SSL_NOTYETVALID -> "The certificate is not yet valid."
            SslError.SSL_DATE_INVALID -> "The date of the certificate is invalid"
            SslError.SSL_INVALID -> "A generic error occurred"
            else -> "A generic error occurred"
        }
        message += " Do you want to continue anyway?"
        builder.setTitle("SSL Certificate Error")
        builder.setMessage(message)
        builder.setPositiveButton("Continue") { dialog, which -> handler.proceed() }
        builder.setNegativeButton("Cancel") { dialog, which -> handler.cancel() }
        val dialog = builder.create()
        dialog.show()
    }

    private fun loadUrl(href: String?) {
        if (!TextUtils.isEmpty(href)) {
            try {
                Log.e(TAG, "web 加载的链接 $href")
                mWeb!!.loadUrl(href!!)
            } catch (e: Exception) {
            }
        }
    }

    public override fun onDestroy() {
        super.onDestroy()
        if (binding!!.web != null) {
            binding!!.web.removeView(mWeb)
        }
        mWeb!!.stopLoading()
        mWeb!!.clearHistory()
        mWeb!!.clearFormData()
        mWeb!!.clearView()
        mWeb!!.removeAllViews()
        try {
            mWeb!!.destroy()
        } catch (e: Exception) {
        }
    }

    override fun finish() {
        val view = window.decorView as ViewGroup
        view.removeAllViews()
        super.finish()
    }

    companion object {
        //p133
        fun startActivity(context: Context, vararg args: Any?) {
            val intent = Intent(context, WebActivity::class.java).apply {
                putExtra(Constants.PARAM_DATA1, args[0] as String?)
               putExtra(Constants.PARAM_DATA2, args[1] as String?)
            }

            context.startActivity(intent)
        }

        private const val TAG = "WebActivity"
    }
}